package com.dyz.LeetCodeforSwordFingerOffer;

import java.util.HashMap;
import java.util.Map;

public class MajorityElement39 {
    //思路通过hash统计频数
    public int majorityElement(int[] nums) {
        //处理特殊值
        if(nums==null || nums.length==0){
            return -1;
        }
        if(nums.length==1){
            return nums[0];
        }
        HashMap<Integer, Integer> map = countNums(nums);
        Map.Entry<Integer, Integer> majorityEntry = null;
        for (Map.Entry<Integer, Integer> integerIntegerEntry : map.entrySet()) {
            if(majorityEntry==null || integerIntegerEntry.getValue()>majorityEntry.getValue()){
                majorityEntry = integerIntegerEntry;
            }
        }
        return majorityEntry.getKey();
    }
    private HashMap<Integer, Integer>  countNums(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i <nums.length ; i++) {
            if(map.containsKey(nums[i])){
                map.put(nums[i], map.get(nums[i])+1);
            }else {
                map.put(nums[i], 1);
            }
        }
        return map;
    }
}
